package com.example.lotterysystem;

import com.example.lotterysystem.common.pojo.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

@SpringBootTest
public class Jackson {

    @Test
    void jacksonTest() {
        ObjectMapper objectMapper = new ObjectMapper();
        CommonResult<String> result = CommonResult.error(500,"系统错误");
        String str;

        //序列化
        try {
            str = objectMapper.writeValueAsString(result);
            System.out.println(str);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        //反序列化
        try {
            CommonResult<String> read = objectMapper.readValue(str,CommonResult.class);
            System.out.println(read.getCode() + read.getMsg() + read.getData());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        //序列化list
        List<CommonResult<String>> list = Arrays.asList(
                CommonResult.success("success1"),
                CommonResult.success("success2")
        );
        try {
            str = objectMapper.writeValueAsString(list);
            System.out.println(str);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        //反序列化list
        JavaType javaType = objectMapper.getTypeFactory()
                .constructParametricType(List.class,CommonResult.class);
        try {
            list = objectMapper.readValue(str,javaType);
            for (CommonResult<String> list1 : list) {
                System.out.println(list1.getData());
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    void JacksonUtilTest() {
        CommonResult<String> result = CommonResult.success("success");
        String str;

        //序列化
        str = JacksonUtil.writeValueAsString(result);
        System.out.println(str);

        //反序列化
        result = JacksonUtil.readValue(str,CommonResult.class);
        System.out.println(result.getData());

        //序列化LIST
        List<CommonResult<String>> list = Arrays.asList(
                CommonResult.success("success1"),
                CommonResult.success("success2")
        );
        str = JacksonUtil.writeValueAsString(list);
        System.out.println(str);

        //反序列化LIST
        list = JacksonUtil.readListValue(str, CommonResult.class);
        for (CommonResult<String> commonResult : list) {
            System.out.println(commonResult.getData());
        }
    }
}
